package com.yifeng.repo.micro.service.server.auth.ucs.config;

import com.yifeng.repo.micro.service.server.auth.ucs.interceptor.UcsAuthInterceptor;
import com.yifeng.repo.micro.service.server.auth.ucs.interceptor.cache.UcsCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * create by zyh @2022.09.18
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({UcsAuthProperties.class})
public class UcsAuthConfiguration implements WebMvcConfigurer {
    private final UcsAuthProperties properties;

    public UcsAuthConfiguration(UcsAuthProperties properties) {
        this.properties = properties;
    }

    @Override
    public void addInterceptors(@NotNull InterceptorRegistry registry) {
        if(!properties.getEnableAuth()) {
            return;
        }

        UcsCache.getInstance().init(properties.getUrl(), properties.getCacheSize());
        List<String> excludePathPatterns = new ArrayList<>();
        excludePathPatterns.add("/");
        excludePathPatterns.add("/index.html");
        excludePathPatterns.addAll(properties.getIgnorePatterns());
        registry.addInterceptor(new UcsAuthInterceptor())
                .addPathPatterns(properties.getPatterns())
                .excludePathPatterns(excludePathPatterns);
        log.info("******* UcsAuthInterceptor init success *******");
    }
}
